package com.mbc.web.common.client.ui.control;

import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.TextBox;

public class MTextBox extends TextBox {
	
	private HandlerRegistration numberKeyPressHandlerRegistration;
	private HandlerRegistration numberChangeHandlerRegistration;
	private HandlerRegistration numberFocusHandlerRegistration;
	
	public void setRequired(boolean required)
	{
		if(required)
			this.getElement().setAttribute("required", "");
		else
			this.getElement().removeAttribute("required");
	}
	
	public void setPlaceholder(String placeholder){
		this.getElement().setAttribute("placeholder", placeholder);
	}
	
	public void setTabindex(String tabindex){
		this.getElement().setAttribute("tabindex", tabindex);
	}
	
	public void setNumber(boolean isNumber){
		if(isNumber){
			numberKeyPressHandlerRegistration = this.addKeyPressHandler(new KeyPressHandler() {
		
			@Override
			public void onKeyPress(KeyPressEvent event) {
				int l_keyCode = event.getNativeEvent().getKeyCode();
				if(l_keyCode != KeyCodes.KEY_BACKSPACE &&
								l_keyCode != KeyCodes.KEY_ENTER &&
								l_keyCode != KeyCodes.KEY_DELETE &&
								l_keyCode != KeyCodes.KEY_LEFT &&
								l_keyCode != KeyCodes.KEY_RIGHT &&
								l_keyCode != KeyCodes.KEY_HOME &&
								l_keyCode != KeyCodes.KEY_END &&
								l_keyCode != KeyCodes.KEY_SHIFT &&
								l_keyCode != KeyCodes.KEY_TAB ){
						if(event.getCharCode() == '.'){
							if(MTextBox.this.getText().indexOf('.') != -1)
								MTextBox.this.cancelKey();
						}else{
							if(!Character.isDigit(event.getCharCode()))
								MTextBox.this.cancelKey();
						}
					}
				}
			});
			
			numberChangeHandlerRegistration = this.addChangeHandler(new ChangeHandler() {
		
				@Override
				public void onChange(ChangeEvent event) {
					if(MTextBox.this.getText().equals(""))
						MTextBox.this.setText("0");
				}
			});
			
			numberFocusHandlerRegistration = this.addFocusHandler(new FocusHandler() {
				
				@Override
				public void onFocus(FocusEvent event) {
					if(!MTextBox.this.getText().equals("")){
						double l_val = Double.parseDouble(MTextBox.this.getText());
						if(l_val == 0)
							MTextBox.this.selectAll();
					}
				}
			});
		}
		else{
			if(numberKeyPressHandlerRegistration != null){
				numberKeyPressHandlerRegistration.removeHandler();
				numberChangeHandlerRegistration.removeHandler();
				numberFocusHandlerRegistration.removeHandler();
			}
		}
	}
}
